using System;
using System.Threading.Tasks;
using ByteDance.Live.Foundation.Logging;
using ByteDance.LiveOpenSdk.Runtime.Utilities;
using Douyin.LiveOpenSDK.Samples;
using QFramework;
using UnityEngine;

// 初始化设置  包括登录和链接websocket
public class GameStartup : MonoBehaviour
    {
        // private SetRoomIdSocket setRoomIdSocket;

        private async void Start()
        {
            Screen.SetResolution(1080, 1920, FullScreenMode.Windowed);
            // 可设置日志等级，调试时可使用较详细的日志
            SdkUnityLogger.MinSeverity = Severity.Verbose;
            // 任何玩法需设置
            string appId = "tt2692502fb99986b010";
            // 初始化直播开放 SDK
            print($"开始LiveOpenSdk初始化 AppId: {appId}");
            SampleLiveOpenSdkManager.Initialize(appId);
            ToastManager.Instance.ShowToast("玩法初始化中...");
            //初始化 httpclient
            // 初始化配置（通常放在程序启动时）
            HttpClientService.Instance
                .SetBaseUrl("https://api.question.game.xmnk.cn/")
                .SetTimeout(TimeSpan.FromSeconds(30));
            

           if (string.IsNullOrEmpty(SampleLiveOpenSdkManager.Token))
            {
                print("警告：SDK 未能从命令行获得 token，请从直播伴侣启动 exe 或手动提供 token");
                print("手动复制token：15225006562");
                SampleLiveOpenSdkManager.Token = "15225006562";
            }
            //初始化后台获取后台给的token和romid
            var res = await QueryTokenAsync();
            //获取token和romoid后进行长链接
            if (res){
                // 注册连接成功回调
                WebSocketManager.Instance.OnConnected += OnWebSocketConnected;
                // 初始化连接
                WebSocketManager.Instance.Connect();
            }

            StringEventSystem.Global.Register(EventID.ReLogin, () => {
                Debug.Log("开始重新登录");
                SampleLiveOpenSdkManager.Initialize(appId);
                _ = QueryTokenAsync();  
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        
         async Task<bool> QueryTokenAsync()
        {
            ToastManager.Instance.ShowToast("玩法登陆中...");
            try
            {
                var newUser = new { token = SampleLiveOpenSdkManager.Token };
                var postResponse = await HttpClientService.Instance
                    .Post("/auth/login")
                    .SetBody(newUser)
                    .SendAsync();
                
                if (!postResponse.IsSuccess)
                {
                    print("登录请求失败");
                    return false;
                }
                ToastManager.Instance.ShowToast("玩法登陆成功");

                print("postResponse:" + postResponse.GetJson());
                // 解析JSON数据
                LoginResponse RspData = JsonUtility.FromJson<LoginResponse>(postResponse.GetJson());
                string access_token = RspData.data.token.access_token;
                string room_id = RspData.data.room_id;

                print("access_token:" + access_token);

                if (string.IsNullOrEmpty(access_token) || string.IsNullOrEmpty(room_id))
                {
                    print("获取的token或room_id为空");
                    return false;
                }

                GlobalData.SetAccessToken(access_token);
                GlobalData.SetRoomId(room_id);
                
                HttpClientService.Instance.AddDefaultHeader("Authorization", "Bearer " + access_token);
                return true;
            }
            catch (Exception ex)
            {
                print($"QueryTokenAsync异常: {ex.Message}");
                ToastManager.Instance.ShowToast("登录异常："+ex.Message);
                return false;
            }
        }

        // 添加WebSocket连接成功回调方法
        private void OnWebSocketConnected()
        {
            _ = SetRoomIdSocket.SendSetRoomIdAsync(long.Parse(GlobalData.RoomId));
        }

        private void OnDestroy()
        {
            // 记得在销毁时取消注册
            if(WebSocketManager.Instance != null)
            {
                WebSocketManager.Instance.OnConnected -= OnWebSocketConnected;
            }
        }
    }

// 登录返回数据 
// 登录返回数据（保持与JSON完全一致的字段名和层级）
[System.Serializable]
public class LoginResponse
{
    public int status;  // 对应JSON中的"status"
    public LoginResponseData data;  // 对应JSON中的"data"
}

[System.Serializable]
public class LoginResponseData
{
    public LoginTokenInfo token;  // 对应JSON中的"token"
    public string room_id;  // 对应JSON中的"room_id"
}

[System.Serializable]
public class LoginTokenInfo
{
    public string token_type;  // 对应JSON中的"token_type"
    public int expires_in;     // 对应JSON中的"expires_in"
    public string access_token; // 对应JSON中的"access_token"
}